﻿using System;
using System.Drawing;
using System.Windows.Forms;

class StartUp
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    public static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            //Configure
            if (args[0].ToLower().Trim().Substring(0, 2) == "/c")
            {
                Application.Run(new ConfigForm());
            }
            //Run it
            else if (args[0].ToLower() == "/s")
            {
                RunScreenSaver();
            }
            //Preview it
            else if (args[0].ToLower() == "/p")
            {
                //Get the preview window hwnd and rectangle
                IntPtr parent = (IntPtr)uint.Parse(args[1]);
                Rectangle prevRect = Rectangle.Empty;
                User32.GetClientRect(parent, ref prevRect);

                Application.Run(new MatrixScreen(prevRect, Environment.TickCount, true, parent));
            }
        }
        else//TODO: Install it?
        {
            RunScreenSaver();
        }
    }


    public static void RunScreenSaver()
    {
        //Start each screen on a different thread
#if DEBUG
        System.Threading.Thread[] threads = new System.Threading.Thread[1];
#else
        System.Threading.Thread[] threads = new System.Threading.Thread[Screen.AllScreens.Length];
#endif
        int threadCount = -1;

        object[] param;

        foreach (Screen screen in Screen.AllScreens)
        {
            threadCount++;
            System.Threading.Thread t = new System.Threading.Thread(StartScreen);

            //Send the screen bounds and the screen index
            param = new object[] { screen.Bounds, threadCount };
            
            t.Start(param);

            threads[threadCount] = t;

#if DEBUG
            break;
#endif
        }

        bool isRunning = true;

        //While running check if any of the threads have closed
        while (isRunning)
        {
            foreach (System.Threading.Thread thread in threads)
            {
                if (!thread.IsAlive)
                    isRunning = false;
            }

            Application.DoEvents();
        }

        //If any thread closed, close them all
        foreach (System.Threading.Thread thread in threads)
        {
            thread.Abort();
        }
    }

    public static void StartScreen(object parameters)
    {
        //Start the screen
        object[] param = (object[])parameters;
        Application.Run(new MatrixScreen((Rectangle)param[0], (int)param[1], false, IntPtr.Zero));
    }

}

